package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.annotation.LoginUser;
import io.renren.common.utils.ConfigConstant;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.GrabPacketEntity;
import io.renren.entity.MemberEntity;
import io.renren.entity.SendPacketEntity;
import io.renren.form.SendPacketForm;
import io.renren.service.GrabPacketService;
import io.renren.service.MemberService;
import io.renren.service.SendPacketService;
import io.renren.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.annotations.ApiIgnore;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * 会员接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api/packet")
@Api(tags = "红包接口")
public class ApiPacketController extends AbstractController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private SendPacketService sendPacketService;

	@Autowired
	private GrabPacketService grabPacketService;

	@Autowired
	private SysConfigService sysConfigService;

	@SuppressWarnings("unchecked")
	@Login
	@PostMapping("list")
	@ApiOperation("红包列表")
	public R list(@ApiIgnore @RequestAttribute("userId") Long userId, @ApiIgnore @RequestParam Map<String, Object> params) {
		params.put("memberId", userId);
		PageUtils page = sendPacketService.myPacketPage(params);
		List<SendPacketEntity> list = (List<SendPacketEntity>) page.getList();
		if (CollectionUtils.isNotEmpty(list)) {
			for (SendPacketEntity sendPacketEntity : list) {
				MemberEntity entity = memberService.selectById(sendPacketEntity.getMemberId());
				sendPacketEntity.setNickname(entity.getNickname());
				sendPacketEntity.setHeadImg(entity.getHeadImg());
				if (!userId.equals(sendPacketEntity.getMemberId())) {
					GrabPacketEntity grabPacketEntity = grabPacketService.selectOne(new EntityWrapper<GrabPacketEntity>().eq("send_packet_id", sendPacketEntity.getId()).eq("grab_member_id", userId));
					sendPacketEntity.setMyGrabAmount(grabPacketEntity == null ? 0 : grabPacketEntity.getGrabAmount());
					sendPacketEntity.setIsLandmine(grabPacketEntity == null ? 0 : grabPacketEntity.getIsLandmine());
					sendPacketEntity.setLandmineAmount(grabPacketEntity == null ? null : grabPacketEntity.getLandmineAmount());
				}
			}
		}
		return R.ok().put("page", page);
	}

	@Login
	@PostMapping("listGrab")
	@ApiOperation("抢包会员列表")
	public R listGrab(@RequestParam Long id) {
		SendPacketEntity send = sendPacketService.selectById(id);
		Assert.notNull(send, "红包已过期无法查看");
		boolean cannotView = send.getStatus() != ProjectConstant.PACKET_STATUS_INITIAL || System.currentTimeMillis() > DateUtils.addDateMinutes(send.getCreateTime(), sysConfigService.getValueI(ConfigConstant.PACKET_EXPIRE)).getTime() ? false : true;
		if (cannotView) {
			Assert.isTrue(send.getMemberId().equals(getUserId()) || grabPacketService.selectCount(new EntityWrapper<GrabPacketEntity>().eq("send_packet_id", send.getId()).eq("grab_member_id", getUserId())) == 1, "无法查看");
		}
		List<GrabPacketEntity> list = grabPacketService.selectList(new EntityWrapper<GrabPacketEntity>().eq("send_packet_id", id).orderBy("create_time", false));
		if (CollectionUtils.isNotEmpty(list)) {
			for (int i = 0; i < list.size(); i++) {
				GrabPacketEntity grabPacketEntity = list.get(i);
				MemberEntity entity = memberService.selectById(grabPacketEntity.getGrabMemberId());
				grabPacketEntity.setNickname(entity.getNickname());
				grabPacketEntity.setHeadImg(entity.getHeadImg());
			}
		}
		return R.ok().put("list", list);
	}

	@SuppressWarnings("unchecked")
	@Login
	@PostMapping("roomPacketList")
	@ApiOperation("房间初始化红包列表")
	public R roomPacketList(@RequestParam Long roomId, @ApiIgnore @RequestParam Map<String, Object> params) {
		Long userId = getUserId();
		Assert.isTrue(memberService.selectCount(new EntityWrapper<MemberEntity>().eq("id", userId).eq("room_id", roomId)) == 1, "您不在此房间");
		params.put("roomId", roomId);
		PageUtils page = sendPacketService.queryPage(params);
		List<SendPacketEntity> list = (List<SendPacketEntity>) page.getList();
		if (CollectionUtils.isNotEmpty(list)) {
			for (SendPacketEntity sendPacketEntity : list) {
				MemberEntity entity = memberService.selectById(sendPacketEntity.getMemberId());
				sendPacketEntity.setNickname(entity.getNickname());
				sendPacketEntity.setHeadImg(entity.getHeadImg());
				if (!userId.equals(sendPacketEntity.getMemberId())) {
					GrabPacketEntity grab = grabPacketService.selectOne(new EntityWrapper<GrabPacketEntity>().eq("send_packet_id", sendPacketEntity.getId()).eq("grab_member_id", userId));
					sendPacketEntity.setMyGrabAmount(grab == null ? 0D : grab.getGrabAmount());
				} else {
					sendPacketEntity.setMyGrabAmount(0D);
				}
				sendPacketEntity.setCountDown((DateUtils.addDateMinutes(sendPacketEntity.getCreateTime(), sysConfigService.getValueI(ConfigConstant.PACKET_EXPIRE)).getTime() - System.currentTimeMillis()) / 1000);
			}
			Collections.reverse(list);
		}
		return R.ok().put("page", page);
	}

	@Login
	@PostMapping("send")
	@ApiOperation("发红包")
	public R send(@ApiIgnore @LoginUser MemberEntity member, @RequestBody SendPacketForm form) {
		// 校验类型
		ValidatorUtils.validateEntity(form);
		sendPacketService.send(member, form.getRoomId(), Math.floor(form.getAmount()), form.getLandmine(), form.getPacketQty());
		return R.ok().put("sender", member);
	}

	@Login
	@PostMapping("grab")
	@ApiOperation("抢红包")
	public R grab(@ApiIgnore @LoginUser MemberEntity member, @RequestParam Long id) {
		Assert.notNull(id, "红包ID不能为空");
		logger.info("method grab executing");
		long start = System.currentTimeMillis();
		GrabPacketEntity grab = grabPacketService.grab(member, id);
		logger.info("method grab execute time:" + (System.currentTimeMillis() - start));
		return R.ok().put("grab", grab).put("grabMember", member);
	}
}
